package com.cans.lightning.config.security;

import com.cans.lightning.config.security.filter.JwtAuthenticationTokenFilter;
import com.cans.lightning.config.security.handler.AuthenticationEntryPointImpl;
import com.cans.lightning.config.security.handler.AuthenticationFailureHandler;
import com.cans.lightning.config.security.handler.AuthenticationSuccessHandler;
import com.cans.lightning.business.pms.service.api.ISysUserService;
import org.springframework.context.annotation.Bean;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDecisionVoter;
import org.springframework.security.access.vote.AuthenticatedVoter;
import org.springframework.security.access.vote.UnanimousBased;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.access.expression.WebExpressionVoter;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;

/**
 * spring security 核心配置类
 *
 * @author shencan
 * @date 2020/6/20 21:51
 */

@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Resource
    private ISysUserService sysUserService;
    @Resource
    private JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;



    /**
     * 登陆成功
     *
     * @return
     */
    @Bean
    public SimpleUrlAuthenticationSuccessHandler authenticationSuccessHandler() {

        return new AuthenticationSuccessHandler();
    }

    /**
     * 登陆失败
     *
     * @return
     */
    @Bean
    public SimpleUrlAuthenticationFailureHandler authenticationFailure() {
        return new AuthenticationFailureHandler();
    }

    /**
     * 解决 无法直接注入 AuthenticationManager
     */
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(sysUserService).passwordEncoder(passwordEncoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.cors().and().csrf().disable();

        // 禁用session
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

        http.authorizeRequests()
                .antMatchers("/file/**", "/getAllUser", "/pms/**", "/register",
                        "/doc.html", "/api-docs")
                .permitAll() // 不需要身份认证
                .anyRequest().authenticated();

        http.authorizeRequests().accessDecisionManager(accessDecisionManager());
        // 认证失败处理类
        http.exceptionHandling().authenticationEntryPoint(new AuthenticationEntryPointImpl());
        // 调用成功和失败处理器
        http.formLogin().successHandler(authenticationSuccessHandler()).failureHandler(authenticationFailure());

        // 添加jwt token filter
        http.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);

    }

    @Bean
    public PasswordEncoder passwordEncoder() {

        return new BCryptPasswordEncoder();
    }


    @Bean
    public AccessDecisionManager accessDecisionManager() {
        List<AccessDecisionVoter<? extends Object>> decisionVoters
                = Arrays.asList(
                new WebExpressionVoter(),
                // new RoleVoter(),
                new RoleBasedVoter(),
                new AuthenticatedVoter());
        return new UnanimousBased(decisionVoters);
    }
}
